<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-09-14 10:32:58
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-06-08 10:00:46
 */

namespace Ldy\Models;

use Ldy\Model;
use Ldy\Models\SysMenuApi;
use Ldy\Traits\Model\Trees;
// use Ldy\Models\SysRoleMenu;
// use Ldy\Models\SysApi;
use tauthz\facade\Enforcer as Permission;

class SysMenu extends Model{

	use Trees;

	protected $json = ['meta'];
    
    // public function setParentIdAttr($val){
	// 	if(!is_array($val)) return $val;
	// 	$count = count($val);
	// 	return $val[$count-1];
	// }

	

	public function getApisAttr($val){
		if(is_array($val)) return $val;
		return empty($val) ? []:explode(',', $val);
	}

	/**
	 * 更新前处理
	 *
	 * @param [type] $model
	 * @return void
	 */
	public static function onBeforeUpdate($model){
		$id = $model->id;
		$menuRoleApis = self::getMenuRoleApis($id);
		if(!empty($menuRoleApis)){
			foreach($menuRoleApis as $item){
				$roleName = casbin_role_field_prefix($item->role_id);
				Permission::deletePermissionForUser($roleName, $item->path,$item->action);
			}
		}
	}

	//数据更新后操作
	public static function onAfterUpdate($model){
		$apis_id = request()->param('apis');
		$id = request()->param('id',0);
		if(empty($id)) return false;
	
		$sysmenuapi = new SysMenuApi();
		$sysmenuapi->where('menu_id', $id)->delete();

		if(empty($apis_id)) return false;
		
		$data = [];
		foreach($apis_id as $val) $data[] = ['menu_id' => $id, 'api_id'=>$val];
		$sysmenuapi->saveAll($data);

		//找到该菜单中的所有角色
		// $data = SysRoleMenu::where('menu_id', $id)->select();
		// if($data->isEmpty()) return false;
		
		// $apisData = SysApi

		$dbData = self::getMenuRoleApis($id);
		
// print_r($dbData->toArray());
		if($dbData->isEmpty()) return false;
		$rules = [];
		// $role_ids = [];
		foreach($dbData as $item){
			$action = $item->action == 'ALL' ? "GET|POST|PUT|DELETE":$item->action;
			$roule_name = casbin_role_field_prefix($item->role_id);
			$rules[] = [$roule_name, $item->path, $action];
		}

		Permission::addPolicies($rules);
	}

	public static function getMenuRoleApis($menu_id){

		$dbData = self::alias('m')
		->field('a.path,rm.role_id,a.action, a.id as aid')
		->join('sys_role_menu rm', 'm.id=rm.menu_id')
		->join('sys_menu_api ma','ma.menu_id=m.id')
		->join('sys_api a', 'a.id=ma.api_id')
		->where('m.id', $menu_id)
		->select();

		return $dbData;
	}

	public function getUserMenu(Array $roleIds = []){

		if(empty($roleIds)) return [];
		
		//全部菜单数据
        $data = SysMenu::select()->toArray();
		$menuIds = [];

		$roleMenu = SysRoleMenu::whereIn('role_id', $roleIds)->select();
        if(!$roleMenu->isEmpty()) foreach($roleMenu as $item) $menuIds[] = $item->menu_id;
		// print_r($menuIds);
		$arr = [];
		foreach($menuIds as $id){
			$arr = array_merge($this->sonNode($data, $id), $arr);
		}
		//按ID值去重
		$newMenus = [];
		foreach($arr as $item){
			$newMenus[$item['id']] = $item;
		}

		$newMenus = $this->array_sort($newMenus, 'id');
		
		$userMenu = $this->children($newMenus,0);

		$userMenu = $this->array_sort($userMenu,'rand');
		// print_r($userMenu);

		return $userMenu;
    }

	private function sonNode($data, $id){
		$arr = [];
		foreach($data as $item){
			if($item['id']==$id){
				$arr[]=$item;// $arr[$v['id']]=$v['name'];
				$arr=array_merge($this->sonNode($data,$item['parent_id']), $arr);
			}
		}

		return $arr;
	}


	protected function setTreesData(){
		$data = $this->alias('m')
        ->field('m.*,GROUP_CONCAT(a.api_id) AS apis')
        ->leftJoin('sys_menu_api a','m.id=a.menu_id')
        ->group('m.id')
        ->select();

		return $data->isEmpty() ? []:$data->toArray();
	}

	
	
}